package com.zhuimeng.Application.contorller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.zhuimeng.Application.entity.HappyBeanHistory;
import com.zhuimeng.Application.entity.RechargeOrder;
import com.zhuimeng.Application.service.IHappyBeanHistoryService;
import com.zhuimeng.Application.service.IRechangeOrderService;
import com.zhuimeng.Application.service.IUserSelvice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/order")
@CrossOrigin
public class ReChangeOrderController {

    @Autowired
    private IRechangeOrderService rechangeOrderService;

    @Autowired
    private IHappyBeanHistoryService happyBeanHistoryService;

    @Autowired
    private IUserSelvice userSelvice;

    @RequestMapping("/create")
    public String createOrder(Integer uid, double money) {

        BigDecimal moneyBD = BigDecimal.valueOf(money);
        BigDecimal numberBD = BigDecimal.valueOf(100);

        String orderId = UUID.randomUUID().toString();
        RechargeOrder rechargeOrder = new RechargeOrder();
        rechargeOrder.setUserId(uid);
        rechargeOrder.setMoney(moneyBD);
        rechargeOrder.setOrderId(orderId);
        rechargeOrder.setStatus(0);
        rechargeOrder.setCreateTime(new Date());
        rechargeOrder.setBeanNumber(moneyBD.multiply(numberBD).intValue());

        rechangeOrderService.insertOrder(rechargeOrder);

        rechangeOrderService.alipayOrder(orderId);

        return orderId;
    }

    @RequestMapping("/list")
    public List<RechargeOrder> queryList(Integer uid) {
        System.out.println(uid);
        return rechangeOrderService.queryRechangeORderByUid(uid);
    }

    @RequestMapping("/pay")
    public void payOrder(String orderId, HttpServletResponse response) throws IOException {

        RechargeOrder rechargeOrder = rechangeOrderService.getByOrderId(orderId);


        AlipayClient alipayClient =
                new DefaultAlipayClient(
                        "https://openapi.alipaydev.com/gateway.do",
                        "2021000118674734",
                        "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDRWtpFygEynRzUdNWCMSVcWCVE77zTw9N/zugJNpaYh9+Jen4/+CByCXQ59cYI8BlYF0f+80oSuIa1OD0XfpE77g0n30VL2m+aHhxvchlnaH0Y0+wS1GXnf0xMPt75J1KLqlwQnRLeruDUTSEq2QZCCGz/1OQr71KU8sbCnl3xFchjhv70Jq0tlb8iRtdXxO+jC+pjsREM93m7WwW2abDFasSfeJuDvsSh5/3xJ7EB92bYc0NIykzN/geAF80bzo3xoQ09O1RsRRFwfraPpGHZmZXqPzbfNIgBsujKI3EuXQ7wVs3IdY0FnPAyNXgbzM8r5lrOPHnDVC3YBVl2FoN5AgMBAAECggEBAMwAQNNijRo52J76HhcYNrSuO9rZ1WFw38YZ4ycfJ04IkH1RfHZvHYahyby0zj1lYPzi6sf3YEWvw6wQ2g7ryS/hvrYMrWTFvJwsHT9HqpOGUOgBkXejuo0DEWD2nqWgeKIZ5k5WEM4nEHQvmFM9WQi9VyFP3Osm8IytqZp5YUcKVJjUu5xkIuOn8u2dL/816QIuZZipRcVFVHck8vkt4NDHa6y/lXQ/AoUUgGnf7jRORM2NAOl1CpYoCJT4cpIyKRXRQM2V/jL9EnS1YmsPSCfn8/eodzX+dbx2oIhFBQGWxI+Eo/8qfiluHGZdG3EenEakZWgu94309Jtxz6id3gUCgYEA6vr/w908LjcIJiAXUBFz9mYEU7GP1rCbE2wLWGIZPJrhHccFMCZdWkYTBdZKL89eN5i3KoQrPL9vvRRy5ec+inKL7W3rDzbK5AEFPH27QQDZoRrNdib2oar26yM/sqvHtXfY4fkbbkmmjNuUq39SLjL+5T7TV3ACv0lF0NM92c8CgYEA5BUImRfa5Je4RJ1wOfswg6N8jjqsxPGPgfjUarlj8KuBPmDA/K9gc0cZSqSH5wae9/xUQeM0NeHZJnyGUpNxEsYQNgrxojgOylx0L1FdnMh5Wv9xX1zGxixaU6ShaTfqBEvqDMdBqWAqfm9ysBm08BdS0fh4J9+yao8v/VPtyDcCgYEA2kpGY9wYVg6FoXVacuVjxtjK2D0xlI4H4ikS+Q5Yx3ZR/umuJibdvkkuztNdo8COlDNopTSXPh3RXeOrQWxrKw5ycyUTotSR8vIHvURIOoDhq8pMaKCVqWY7cAEU4ZS3OBuX/YT/OJtu/5fVKuRiocx6Atk0WBwUUUNueipjYP0CgYBX2c4tAaY7ZEEClM20V49RNPh15B3F4fFPs6NF1FCtU7H9b9EFwxtYa6tPN95s2v0CMbvWgQgMNQiqLU6joczs2UNHPaHixMrVoRTTYPi4ufMcXMWzYI3jqRPFoeTWHUZTD1aAQ4OEFNlpR84aDFzIGYO6AoVtflk/eBWY8unkswKBgQCpP5lyBu7cFBxllD7Se2UE3aHPG8w6uuFkGI5l9wG8rL16wAbxR6S4+42y1m1vuouAZdxITnjdM9Op7AOQssf4gRpH/FEX6GhHq7HvV9GgxloXDrMZfR/uCh4m8lp3cALW4WdkHzhazQftzEuwB2k/WMMXVhT1ohwk6EIUsKK+tA==",
                        "json",
                        "utf-8",
                        "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjo54IvNJXO063YxtbLMtxVXznUxgchlX639af/EWGtzkDXj2LS18Yyxb40QhGPziEh4CoMScPixRcGOmnsOClPsG7z3K+MBgWWuykA0aUsihAax6ed43lyhS+yveBgmeELd20FrzBcXI11i/xGCO4H34LJtdTq7Q9H6+Pu7lmxxQ1KPC86O9q4m1aJtQMkCtF0P+lN6kAam73r7JDG3Gi5zW8PDbkTKMDeJyUFHQbTde6uMiamiNJdB9QsMKTDW8M/cog03I/GuGvbAfylJZWcqOfyFSCayHTuPGLs+S8gud5efo50af2FMFLOx6XCt2BY3cu8+0H9RQmYcQDIUWjwIDAQAB",
                        "RSA2");  //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest(); //创建API对应的request
        alipayRequest.setReturnUrl("http://www.baidu.com");
        alipayRequest.setNotifyUrl("http://www.baidu.com"); //在公共参数中设置回跳和通知地址
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":\"" + rechargeOrder.getOrderId() + "\"," +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "    \"total_amount\":\"" + rechargeOrder.getMoney().doubleValue() + "\"," +
                "    \"subject\":\"欢乐豆" + rechargeOrder.getBeanNumber() + "个\"" +
                "  }"); //填充业务参数
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(form); //直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }

    @RequestMapping("/pay/query")
    public int payResult(String orderId) throws AlipayApiException {
        AlipayClient alipayClient =
                new DefaultAlipayClient(
                        "https://openapi.alipaydev.com/gateway.do",
                        "2021000118674734",
                        "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDRWtpFygEynRzUdNWCMSVcWCVE77zTw9N/zugJNpaYh9+Jen4/+CByCXQ59cYI8BlYF0f+80oSuIa1OD0XfpE77g0n30VL2m+aHhxvchlnaH0Y0+wS1GXnf0xMPt75J1KLqlwQnRLeruDUTSEq2QZCCGz/1OQr71KU8sbCnl3xFchjhv70Jq0tlb8iRtdXxO+jC+pjsREM93m7WwW2abDFasSfeJuDvsSh5/3xJ7EB92bYc0NIykzN/geAF80bzo3xoQ09O1RsRRFwfraPpGHZmZXqPzbfNIgBsujKI3EuXQ7wVs3IdY0FnPAyNXgbzM8r5lrOPHnDVC3YBVl2FoN5AgMBAAECggEBAMwAQNNijRo52J76HhcYNrSuO9rZ1WFw38YZ4ycfJ04IkH1RfHZvHYahyby0zj1lYPzi6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6GhHq7HvV9GgxloXDrMZfR/uCh4m8lp3cALW4WdkHzhazQftzEuwB2k/WMMXVhT1ohwk6EIUsKK+tA==",
                        "json",
                        "utf-8",
                        "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjo54IvNJXO063YxtbLMtxVXznUxgchlX639af/EWGtzkDXj2LS18Yyxb40QhGPziEh4CoMScPixRcGOmnsOClPsG7z3K+MBgWWuykA0aUsihAax6ed43lyhS+yveBgmeELd20FrzBcXI11i/xGCO4H34LJtdTq7Q9H6+Pu7lmxxQ1KPC86O9q4m1aJtQMkCtF0P+lN6kAam73r7JDG3Gi5zW8PDbkTKMDeJyUFHQbTde6uMiamiNJdB9QsMKTDW8M/cog03I/GuGvbAfylJZWcqOfyFSCayHTuPGLs+S8gud5efo50af2FMFLOx6XCt2BY3cu8+0H9RQmYcQDIUWjwIDAQAB",
                        "RSA2");  //获得初始化的AlipayClient
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderId);
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            String tradeStatus = response.getTradeStatus();
            if (tradeStatus.equals("TRADE_SUCCESS")) {
                RechargeOrder order = rechangeOrderService.getByOrderId(orderId);
                rechangeOrderService.updateOrderStatus(orderId, 1);

                HappyBeanHistory happyBeanHistory = new HappyBeanHistory();
                happyBeanHistory.setuId(order.getUserId());
                happyBeanHistory.setBeanNumber(order.getBeanNumber());
                happyBeanHistory.setType(0);
                happyBeanHistory.setSource(0);
                happyBeanHistory.setCreateTime(new Date());
                happyBeanHistoryService.insertHistory(happyBeanHistory);

                int newhappyBean = userSelvice.updataHappyBean(order.getUserId(), order.getBeanNumber());
                return newhappyBean;
            }
        } else {
            System.out.println("调用失败");
            return -1;
        }
        return -2;
    }
}
